package kyssion.leetcode.num51_100;

public class code59_螺旋矩阵2 {

    public static void main(String[] args) {
        int[][] ins = new code59_螺旋矩阵2().generateMatrix(4);
        for (int a = 0; a < ins.length; a++) {
            for (int b = 0; b < ins[a].length; b++) {
                System.out.print(" "+ins[a][b]);
            }
            System.out.println();
        }
    }

    public int[][] generateMatrix(int n) {
        int[][] arr = new int[n][n];
        int left = 0, right = n - 1;
        int top = 0, botton = n - 1;
        int index = 1;
        while (left < right && top < botton) {
            for (int a = left; a < right; a++) {
                arr[top][a] = index++;
            }
            for (int a = top; a < botton; a++) {
                arr[a][right] = index++;
            }
            for (int a = right; a > left; a--) {
                arr[botton][a] = index++;
            }
            for (int a = botton; a > top; a--) {
                arr[a][left] = index++;
            }
            left++;
            top++;
            right--;
            botton--;
        }
        if (left == right) {
            for (int a = top; a <= botton; a++) {
                arr[a][left] = index++;
            }
        } else if (top == botton) {
            for (int a = left; a <= right; a++) {
                arr[top][a] = index++;
            }
        }
        return arr;
    }
}
